package com.jiezuo.flowable.listener;

import com.jiezuo.common.utils.SpringUtil;
import com.jiezuo.flowable.mapper.CommonMapper;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.engine.impl.context.Context;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description 职能中心监听器
 * @author 庞留杰
 * @date 2025/2/22 17:34
 * @version V1.0
 **/
@Slf4j
@Component
public class DirectorFunctionalCenterListener implements ExecutionListener {

    @Autowired
    CommonMapper commonMapper;

    @Override
    public void notify(DelegateExecution execution) {
        String processInstanceId = execution.getProcessInstanceId();
        CommonMapper commonMapper = SpringUtil.getObject(CommonMapper.class);
        RuntimeService runtimeService = Context.getProcessEngineConfiguration().getRuntimeService();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        String startUserId = processInstance.getStartUserId();//申请人
        // 查询当前用户的部门信息
        Map<String, Object> depart = commonMapper.findDepartLevelInfoByUserId(startUserId);
        if (depart != null) {
            String level = String.valueOf(depart.get("level"));
            String main_leader = String.valueOf(depart.get("main_leader"));
            String ancestors = String.valueOf(depart.get("ancestors"));
            Boolean is_skip_second_depart = "1".equals(level);//是一级部门
            execution.setVariable("is_skip_second_depart", is_skip_second_depart);//是否跳过二级部门
            if (is_skip_second_depart) {//是一级部门
                execution.setVariable("first_depart", main_leader);//一级部门审核人
                execution.setVariable("second_depart", null);//二级部门审核人
            } else {//如果不是一级部门，那便是二级，接着查一级部门
                execution.setVariable("second_depart", main_leader);//二级部门审核人
                List<Map<String, Object>> departs = commonMapper.findDepartLevelInfoByAncestors(ancestors);
                if (departs.size() > 0) {
                    List<String> list = departs.stream().map(it -> String.valueOf(it.get("main_leader"))).collect(Collectors.toList());
                    String join = String.join(",", list);
                    execution.setVariable("first_depart", join);//一级部门审核人
                }
            }
        }
    }

}
